let fs = require('fs');
let path = require('path')
let router = require('koa-router')();

function searchControllerFile(dir) {
    let file = fs.readdirSync(dir)
    let controller = file.filter((fileName) => {
        return fileName.endsWith('.js') && fileName !== 'index.js';
    })
    return controller;
}

function registeControllerForEachFileOutput(files) {
    files.forEach(item => {
        let tmpPath = path.join(__dirname, item);
        let routerObj = require(tmpPath)
        for (let key in routerObj) {
            let type = routerObj[key][0];
            let fn = routerObj[key][1];
            if (type === 'get') {
                router.get(key, fn)
            } else {
                router.post(key, fn)
            }
        }
    })
}

module.exports = function (defaultDir) {

    let dir = defaultDir || '/controllers';

    let currentPath = path.join('.');

    let endControllerPath = path.join(currentPath, dir)

    let files = searchControllerFile(endControllerPath)

    registeControllerForEachFileOutput(files, endControllerPath);

    return router.routes();
}

// function a() {

//     let file = fs.readdirSync(__dirname)
//     let controller = file.filter((fileName) => {
//         return fileName.endsWith('.js') && fileName !== 'index.js'
//     })

//     controller.forEach(item => {
//         let tmpPath = path.join(__dirname, item);
//         let routerObj = require(tmpPath)
//         for (let key in routerObj) {
//             let type = routerObj[key][0];
//             let fn = routerObj[key][1];
//             if (type === 'get') {
//                 router.get(key, fn)
//             } else {
//                 router.post(key, fn)
//             }
//         }
//     })
//     return router.routes();
// }

// module.exports = a;